math.randomseed(os.time())
tb = {}
function init_orders()
	local path = 'order.dump'
	local file = io.open(path, "r");
	for l in file:lines() do                 --一行一行读取
		order = string.sub(l,0,21)
		uid   = string.sub(l,23,32)
		item  = {order=order, uid=uid}
		table.insert(tb, item)
	end
	file:close()
	out = io.open('out.dump', 'a+')
	print("init_orders finished,order numbers:".. #tb)
end

function dump2file(tb)
	--os.remove('out.dump')
	print("remove done,tb len:".. #tb)
	out = io.open('out.dump', 'a+')
	for key, value in pairs(tb) do      
		print("order:".. value.order)
		out:write(value['order'].. '   '..value['uid']..'\n')
	end  
	out:close()
end

fsof_response = function(body)
	responses = responses + 1
	--[[
	if responses == 10 then
		wrk.thread:stop()
	end
	]]
	--print("fsof body in lua:"..body)
	if body ~= nil and string.find(body,"ok") ==nil then
		orders = orders + 1
		print("failed response:"..body)
	end 
end


fsof_request = function()
	requests = requests + 1
	local orderid = tb[requests].order
	local uid=tb[requests].uid
	--table.remove(tb, requests)
	out:write(tb[requests]['order']..'\n')
	local req = '{"environment":"pre","service":"com.fenqile.fenqile_loan.student_loan.IStudentOrderPayLogicService","method": "handler","params":[{"uid": "3001083","user_type": "0","is_need_update_order_info":"0","sms_send_flag":"","order_id": "O20160922396002900083","channel_id": 1000,"operator": "分期乐·学表二(94906581451)","order_add_result_info":"","name":"分期乐·学表二","passwd_type": "0","pay_pwd":"e10adc3949ba59abbe56e057f20f883e","tag_info":{"test":"colin","channel_id":1000},"modify_time":"2017-02-22 10:33:05","order_type": "80","order_add_result": "SUC"}],"group":"default","version":"1.0.0"}'
	req = (string.gsub(req,'O20160922396002900083', orderid))
	req = (string.gsub(req,'3001083', uid))
	print('req:'.. req)
	return req
end

local threads = {}
local num = 1
function setup(thread)
   thread:set("id", num)
   thread:set("orders", orders)
   thread:set("tb", tb)
   table.insert(threads, thread)
   num = num + 1
end

function init(args)
   requests  = 0
   responses = 0
   orders = 0
   local msg = "thread %d created"
   print(msg:format(id))
	init_orders()
end


function done(summary, latency, requests)
   for index, thread in ipairs(threads) do
      local id        = thread:get("id")
      local requests  = thread:get("requests")
      local responses = thread:get("responses")
	  local orders	  = thread:get("orders")
	--  local tb        = thread:get("tb")
      local msg = "thread %d made %d requests and got %d responses failed %d"
      print(msg:format(id, requests, responses, orders))
   end
	--dump2file(tb)
	--out:close()
end
